<?php

namespace App\Admin\Controllers;

use App\Models\Report;

use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Form;
use Encore\Admin\Facades\Admin;
use App\Models\Squad;
use http\Env\Response;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use DB;
use App\Admin\Extensions\Tools\DeleteReport;


use App\Models\Class_section_group;
use App\Admin\Extensions\DownloadReport;


class ReportController extends Controller
{
    use ModelForm;
    private $class;


    public function __construct(Report $report)
    {
        $this->class = $report;
    }

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        $class = new Admin;
        $class::disablePjax();
        $content->header('报表详情');
        $content->description('详情');
        $content->row($this->form());
        $content->row($this->view());
        return $content;
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {

    }


    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {

    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Squad::class,function (Form $form) {
            $form->setTitle('查看');
            $form->row(function ($row) use ($form)
            {
                $id = Admin::user()->id;
                $row->width(4)->select('section', trans('admin.section'))->options(function(){
                    return Class_section_group::regulate_options(2);
                })->attribute(['id'=>'section'])->Myload('group', '/api/get_group_user',$id)->rules('required');
                $row->width(4)->select('group',trans('admin.group'))->options(function ($id){
                    return Class_section_group::options($id);
                })->attribute(['id'=>'group'])->Myload('squad','/api/get_squads_user',$id)->rules('required');
                $row->width(4)->select('squad',trans('admin.squad'))->attribute(['id'=>'squad'])->load('student','/api/get_students')->rules('required');
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $row->width(4)->select('student','学生id-姓名')->attribute(['id'=>'student'])->rules('required');
                //$row->width(4)->text('start_time','开始时间(包含)')->attribute(['id'=>'startTime']);
                //$row->width(4)->text('end_time','结束时间(包含)')->attribute(['id'=>'endTime']);
                $row->width(4)->date('start_time','开始时间(包含)')->attribute(['id'=>'startTime','style'=>'width:350px;']);
                $row->width(4)->date('end_time','结束时间(包含)')->attribute(['id'=>'endTime','style'=>'width:350px;']);
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $status = array();
                /*                $status[1] = array('1'=>'听写');
                                $status[2] = array('2'=>'测验');
                                $status[3] = array('3'=>'考勤');
                                $status[4] = array('4'=>'家校');
                                $status[5] = array('5'=>'作业');*/
                $status = array('1'=>'听写','2'=>'测验','3'=>'考勤','4'=>'家校','5'=>'作业');
                $row->width(4)->multipleSelect('type','类型')->options($status)
                    ->attribute(['id'=>'type']);
                $row->width(4)->html('<textarea placeholder="请填写评语,填写时使用回车换行，方便排版。" id="memo" style="height:150px;resize:none;width:396px;margin-left:12px;"></textarea>
<span class="nl_zsjc"><i class="nlysrzs">0</i>/<em class="nlzzts">160</em> 个字</span>');
                $row->width(4)->html('<button style="margin-left:170px;" type="button" id="btn_submit" class="btn btn-primary">查询</button><button style="" type="button" id="btn_pdf" class="btn btn-danger" onclick="o_window()">导出PDF</button>');
            },  $form);

            $form->disableSubmit();
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    protected function list()
    {

    }

    protected function view()
    {
        return view('admin::widgets.report');
    }

    public function save(Request $request)
    {
        $op_user = Admin::user()->id;
        $data['op_id'] = $op_user;
        $data['title'] = $request['title'];
        $data['op_time'] = date('Y-m-d H:i:s',time());
        $data['file'] = $request['fileName'];
        //$temp = explode(',',$request['fileName']);
        //$data['file'] = base64_encode($temp[1]);
        Report::create($data);
        return;
    }

    public function get_kaoqin(Request $request){
        return $this->class->get_kaoqin($request);
    }

    public function get_ceyan(Request $request)
    {
        return $this->class->get_ceyan($request);
    }

    public function get_tingxie(Request $request)
    {
        return $this->class->get_tingxie($request);
    }

    public function get_jiaxiao(Request $request)
    {
        return $this->class->get_jiaxiao($request);
    }

    public function get_zuoye(Request $request)
    {
        return $this->class->get_zuoye($request);
    }

    public function down(Request $request)
    {
        $id = $request['id'];
        $data = Report::where('id',$id)->get();

        foreach($data as $v){
            if($v->file != ''){
                $filename = $v->file;

                header("Content-type:application/pdf");
                header("Content-Disposition:attachment;filename = ".$v->title.'.pdf');
                readfile($filename);
            }
        }

        return;
    }

    public function test_report(Request $request,Content $content)
    {
        $content->header('报表详情');
        $content->description('详情');
        $content->row($this->my_form($request));
        $content->row(view('admin.my_test'));
        return $content;
    }

    public function index_new(Request $request,Content $content)
    {
        $content->header('报表详情');
        $content->description('详情');
        $content->row($this->new_form($request));
        $content->row(view('admin.new_test'));
        return $content;
    }

    protected function new_form($request)
    {
        return Admin::form(Squad::class,function (Form $form) use ($request) {
            $form->setTitle('查看');
            $report = Report::where('id',$request['id'])->get()->toArray();
            $parent = Report::where('id',$report[0]['pid'])->get()->toArray();
            $report[0]['section'] = $parent[0]['section'];
            $report[0]['group'] = $parent[0]['group'];
            $report[0]['squad'] = $parent[0]['squad'];
            $report[0]['start_time'] = $parent[0]['start_time'];
            $report[0]['end_time'] = $parent[0]['end_time'];
            $report[0]['type'] = $parent[0]['type'];
            $form->row( function ($row) use ($form,$report)
            {

                $row->width(4)->select('section','班段')->options(function() use ($report){
                    return Class_section_group::where('id',$report[0]['section'])->pluck('name','id');
                })->attribute(['id'=>'section','disabled'=>'true','report_id'=>$report[0]['id']])->default($report[0]['section']);
                $row->width(4)->select('group',trans('admin.group'))->options(function() use ($report){
                    return Class_section_group::where('id',$report[0]['group'])->pluck('name','id');
                })->attribute(['id'=>'group','disabled'=>'true'])->default($report[0]['group']);
                $row->width(4)->select('squad','班级')->options(function() use ($report){
                    return Squad::where('id',$report[0]['squad'])->pluck('name','id');
                })->attribute(['id'=>'squad','disabled'=>'true'])->default($report[0]['squad']);
            },  $form);


            $form->row(function ($row) use ($form,$report)
            {
                $name = explode('-',$report[0]['name']);
                $row->width(4)->select('student','学生id-姓名')->options([$report[0]['student']=>$name[0].'-'.$name[1].'-'.$name[2]])
                    ->attribute(['id'=>'student','disabled'=>'true'])->default($report[0]['student']);
                $row->width(4)->text('开始时间')->default($report[0]['start_time'])->attribute(['id'=>'start_time','disabled'=>'true']);
                $row->width(4)->text('结束时间')->default($report[0]['end_time'])->attribute(['id'=>'end_time','disabled'=>'true']);
            },  $form);

            $form->row(function ($row) use ($form,$report)
            {
                $status = array();
/*                $status[1] = array('1'=>'听写');
                $status[2] = array('2'=>'测验');
                $status[3] = array('3'=>'考勤');
                $status[4] = array('4'=>'家校');
                $status[5] = array('5'=>'作业');*/
                $status = array('1'=>'考勤','2'=>'听写','3'=>'测验','4'=>'家校','5'=>'作业');
                $row->width(4)->multipleSelect('type','类型')->options($status)
                    ->attribute(['id'=>'type','disabled'=>'true'])->default(explode(',',$report[0]['type']));
                $row->width(4)->html('<div id="hid_div" pid="'.$report[0]['pid'].'"></div>');
                $row->width(4)->html('<button style="margin-left:170px;" type="button" id="btn_save" class="btn btn-info">保存评语</button><button style="" type="button" id="btn_pdf" class="btn btn-danger" onclick="o_window()">导出PDF</button>');
            },  $form);

            $form->disableSubmit();
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    protected function my_form($request)
    {
        return Admin::form(Squad::class,function (Form $form) use ($request) {
            $form->setTitle('查看');
            $form->row( function ($row) use ($form,$request)
            {
                $id = Admin::user()->id;
                $name  = Admin::user()->username;

                $squad = DB::table('squads as s')->join('test_assigns as ta','ta.squad_id','=','s.id')
                    ->where('ta.test_config_id',$request['id'])->select('s.id','s.name')->get();
                $options = array();
                foreach($squad as $v){
                    $options[$v->id]=$v->name;
                }
                $row->width(4)->text(trans('admin.teacher'))->default($name)->attribute(['id'=>'teacher','disabled'=>'true','test_id'=>$request['id']]);
                $row->width(4)->select('squad',trans('admin.squad'))->options($options)->attribute(['id'=>'squad'])->load('student','/api/get_students')->rules('required');
                $row->width(4)->select('student','学生id-姓名')->attribute(['id'=>'student'])->rules('required');
            },  $form);


            $form->row(function ($row) use ($form)
            {
                $row->width(4)->textarea('评语  (请老师使用回车分隔，尽量不超过8行，以便排版)')->attribute(['id'=>'memo','style'=>'width:392px;height:150px;resize:none']);
                $row->width(4)->html('<div style="margin-left:20px">如果需要改变颜色，请按照以下方法操作：</div><div style="margin-left:20px">{red|红色的文字}黑色的文字</div><div style="margin-left:20px">暂时只支持红(red)、蓝(blue)、绿(green)三种颜色</div>');
                $row->width(4)->html('<button style="margin-left:15px" type="button" id="btn_pdf" class="btn btn-danger" onclick="">导出PDF</button><button style="" type="button" id="btn_submit" class="btn btn-primary">查询</button>');
            },  $form);

            $form->disableSubmit();
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    public function my_test_submit(Request $request)
    {
        $tests = $squads = array();
        $all_tests = DB::table('test_assigns as ta')->join('notices as n','n.test_assign_id','=','ta.id')
            ->where('ta.test_config_id','=',$request['test'])->select('ta.squad_id','n.id as notice_id')->get();

        //当前班级的notice_id
        $this_test = '';
        foreach($all_tests as $v){
            if($v->squad_id == $request['squad']){
                $this_test = $v->notice_id;
            }
            $tests[] = $v->notice_id;
            $squads[] = $v->squad_id;
        }

        //所有成绩
        $tests_score = array();
        $tests_score = DB::table('test_score_records')->whereIn('notice_id',$tests)->select('notice_id','student_id','test_score')->get();

        $avg = array('所有班级平均成绩'=>0,'当前班级平均成绩'=>0);
        $total = $count = array('all'=>0,'single'=>0);

        //分数分布情况
        $part = array();
        $part['all']['90-100'] = 0;
        $part['all']['80-89'] = 0;
        $part['all']['70-79'] = 0;
        $part['all']['60-69'] = 0;
        $part['all']['0-59'] = 0;
        $part['single']['90-100'] = 0;
        $part['single']['80-89'] = 0;
        $part['single']['70-79'] = 0;
        $part['single']['60-69'] = 0;
        $part['single']['0-59'] = 0;
        foreach($tests_score as $v){
            if($v->notice_id == $this_test){
                if($v->student_id == $request['student']){
                    //统计出选择的这个人
                    $avg['个人成绩'] = $v->test_score;
                }
                //当前的
                if($v->test_score >= 90){
                    $part['single']['90-100'] ++;
                }elseif($v->test_score >= 80 && $v->test_score <= 89){
                    $part['single']['80-89'] ++;
                }elseif($v->test_score >= 70 && $v->test_score <= 79){
                    $part['single']['70-79'] ++;
                }elseif($v->test_score >= 60 && $v->test_score <= 69){
                    $part['single']['60-69'] ++;
                }elseif($v->test_score < 60 && $v->test_score >= 0){
                    $part['single']['0-59'] ++;
                }
                $total['single'] += $v->test_score;
                $count['single']++;
            }
            //汇总的
            if($v->test_score >= 90){
                $part['all']['90-100'] ++;
            }elseif($v->test_score >= 80 && $v->test_score <= 89){
                $part['all']['80-89'] ++;
            }elseif($v->test_score >= 70 && $v->test_score <= 79){
                $part['all']['70-79'] ++;
            }elseif($v->test_score >= 60 && $v->test_score <= 69){
                $part['all']['60-69'] ++;
            }elseif($v->test_score < 60 && $v->test_score >= 0){
                $part['all']['0-59'] ++;
            }
            $total['all'] += $v->test_score;
            $count['all']++;
        }

        $less = $num = array('all'=>0,'single'=>0);
        foreach($tests_score as $v){
            if($v->notice_id == $this_test){
                if($v->student_id == $request['student']){

                }else{
                    if($v->test_score < $avg['个人成绩']){
                        $less['single']++;
                    }
                }
                $num['single']++;
            }
            if($v->student_id == $request['student']){

            }else{
                if($v->test_score < $avg['个人成绩']){
                    $less['all']++;
                }
            }
            $num['all']++;
        }
        $avg['所有班级平均成绩'] = round($total['all']/$count['all'],2);
        $avg['当前班级平均成绩'] = round($total['single']/$count['single'],2);
        $string = '';
        $string .= '该同学在本次考试中超过了{red|'.round( $less['single']/($num['single']-1) * 100 , 2) . "%}的同班同学\n在参与测试的".$num['all']."名同学中,超过了{red|".round( $less['all']/($num['all']-1) * 100 , 2) .'%}的同学';
        return array('status'=>1,'message'=>'操作成功','data'=>array('avg'=>$avg,'part'=>$part,'string'=>$string));
    }

    public function get_kaoqin_stu(Request $request){
        return $this->class->get_kaoqin_stu($request);
    }

    public function get_ceyan_stu(Request $request)
    {
        return $this->class->get_ceyan_stu($request);
    }

    public function get_tingxie_stu(Request $request)
    {
        return $this->class->get_tingxie_stu($request);
    }

    public function get_jiaxiao_stu(Request $request)
    {
        return $this->class->get_jiaxiao_stu($request);
    }

    public function get_zuoye_stu(Request $request)
    {
        return $this->class->get_zuoye_stu($request);
    }

    public function save_memo(Request $request)
    {
        $insert = array();
        for($i=1;$i<7;$i++){
            $insert['memo'.$i] = $request['memo'.$i];
        }
        DB::table('reports')->where('id',$request['pid'])->update(['memo'=>json_encode($insert)]);

        return;
    }

    public function get_memo(Request $request)
    {
        $memo = Report::where('id',$request['pid'])->get(['memo']);
        if(is_null($memo[0]['memo'])){
            return '';
        }else{
            return $memo[0]['memo'];
        }
    }

    //更新导出后状态
    public function export(Request $request)
    {
        DB::table('reports')->where('id',$request['id'])->update(['status'=>1]);
        $pid_o = DB::table('reports')->where('id',$request['id'])->get(['pid']);

        $pid=0;
        foreach($pid_o as $v){
            $pid = $v->pid;
        }

        $count1 = DB::table('reports')->where('pid',$pid)->count();
        $count2 = DB::table('reports')->where('status','=',1)->where('pid',$pid)->count();
        if($count1 == $count2){
            DB::table('reports')->where('id',$pid)->update(['status'=>1]);
        }
        return;
    }
}
